import Foundation

protocol DWJsonSetValue {
    func dw_to_array() -> [Any]
    
    static func dw_subType() -> Any.Type
}
extension DWJsonSetValue where Self: Sequence {
    func dw_to_array() -> [Any] {
        return map { $0 }
    }
    
    static func dw_subType() -> Any.Type {
        if let optionType = self.Element as? DWJsonOptionalValue.Type {
            return optionType.dw_subType()
        }
        return self.Element
    }
}

extension NSSet: DWJsonSetValue {}
extension Set: DWJsonSetValue {}

func dw_set(_ value: Any, type: Any.Type?, subType: Any.Type?) -> DWJsonSetValue? {
    guard let array = value as? [Any] ?? (value as? DWJsonSetValue)?.dw_to_array() else { return nil }
    let list : [Any]
    if let _subType = subType as? DWJsonConvert.Type {
        list = array.compactMap {
            if let dic = dw_valueToDic($0) {
                return _subType.dw_model(dic)
            }
            return nil
        }
    }else {
        list = array
    }
    return type is NSMutableSet.Type ? NSMutableSet(array: list) : NSSet(array: list)
}
